package real.xunlei;

import java.security.interfaces.RSAKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//螺旋数组
public class SpiralArray {
    //给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
    //
    //
    //
    //示例 1：
    //
    //
    //输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
    //输出：[1,2,3,6,9,8,7,4,5]
    public List<Integer> spiralOrder(int[][] matrix) {
        int minL = 0;
        int maxL = matrix.length - 1;
        int minT = 0;
        int maxT = matrix[0].length - 1;
        int i = 0;
        int j = 0;
        boolean need = maxT == 1 && maxL == 1;
        ArrayList<Integer> res = new ArrayList<>(matrix.length * matrix[0].length);
        while (minT <= maxT && minL <= maxL){
            if(i == minL){
                while (j < maxT){
                    System.out.print(matrix[i][j] + " ");
                    res.add(matrix[i][j]);
                    j++;
                }
                minL++;
            }else if(i == maxL){
                while (j > minT){
                    System.out.print(matrix[i][j] + " ");
                    res.add(matrix[i][j]);
                    j--;
                }
                maxL --;
            }
            if(j == maxT){
                while (i < maxL){
                    System.out.print(matrix[i][j] + " ");
                    res.add(matrix[i][j]);
                    i ++;
                }
                maxT --;
            }else if(j == minT){
                while (i > minL){
                    System.out.print(matrix[i][j] + " ");
                    res.add(matrix[i][j]);
                    i --;
                }
                minT ++;
            }
        }
        System.out.println(" ");
//        res.add(matrix[i][j]);
//        if(need){
//            System.out.println();
//            res.add(matrix[1][0]);
//        }
        return res;
    }

    private static void testSpiralOrder() {
        SpiralArray sa = new SpiralArray();
        int[][] matrix1 = {
                {1,2,3},
                {4,5,6},
                {7,8,9}
        };
        List<Integer> expected1 = Arrays.asList(1,2,3,6,9,8,7,4,5);
        sa.spiralOrder(matrix1);

        int[][] matrix2 = {
                {1,2,3,4},
                {5,6,7,8},
                {9,10,11,12}
        };
        List<Integer> expected2 = Arrays.asList(1,2,3,4,8,12,11,10,9,5,6,7);
        sa.spiralOrder(matrix2);

        int[][] matrix3 = {
                {1,2},
                {3,4}
        };
        List<Integer> res = sa.spiralOrder(matrix3);
//        for (Integer re : res) {
//            System.out.println(re);
//        }
    }

    public static void main(String[] args) {
        testSpiralOrder();
    }
}
